package com.htpay.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.htpay.aspect.AutoLog;
import com.htpay.model.common.Constant;
import com.htpay.model.common.DictConstant;
import com.htpay.model.common.ResponseBean;
import com.htpay.model.entity.Merchant;
import com.htpay.model.entity.MerchantWalletInfo;
import com.htpay.service.IMerchantService;
import com.htpay.service.IMerchantWalletService;
import com.htpay.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/merchant")
@Slf4j
public class MerchantController {

    @Autowired
    IMerchantService merchantService;

    @Autowired
    IMerchantWalletService merchantWalletService;

    /**
     * 用户注册接口
     * smsMode 短信模板方式  0 .登录模板、1.注册模板、2.密码重置
     *
     * @param jsonObject
     * @param user
     * @return
     */
    @PostMapping("/register")
    public ResponseBean userRegister(@RequestBody JSONObject jsonObject,
                                     Merchant merchant,
                                     MerchantWalletInfo merchantWalletInfo) {
        ResponseBean bean = new ResponseBean();
        log.info("==== user register json string ====");
        log.info(jsonObject.toJSONString());

        String phone = jsonObject.getString("mobile");
        if (ObjectConvertUtils.isEmpty(phone)) {
            return bean.error("手机号码为必传字段");
        }

        if (phone.length() != 11) return bean.error("手机号为非标准11位号码");

        String smsCode = jsonObject.getString("smscode");
        if (ObjectConvertUtils.isEmpty(smsCode)) {
            return bean.error("短信验证码为必传字段");
        }

        String username = jsonObject.getString("username");
        if (ObjectConvertUtils.isEmpty(username)) {
            return bean.error("用户名为必传字段");
        }
        String password = jsonObject.getString("password");
        if (ObjectConvertUtils.isEmpty("password")) {
            return bean.error("用户密码为必传字段");
        }

        //密码8-12位，且需同时含有字母和数字
        //不满足该正则，会被排除
        if (!ToolUtil.isLetterDigit(password)) {
            return bean.error("密码由8-12位数字、字母组成");
        }

        String email = jsonObject.getString("email");
        if (ObjectConvertUtils.isEmpty(email)) {
            email = "";
        }

        try {

            ///查询用户名是否存在
            Merchant merchant1 = merchantService.getUserByName(username);
            if (merchant1 != null) {
                log.error("--- 用户名【" + username + "】已注册 ---");
                return bean.error("用户名已注册");
            }

            ///判断用户手机号是否注册
            Merchant merchant2 = merchantService.getUserByPhone(phone);
            if (merchant2 != null) {
                log.error("--- 该手机号【" + phone + "】已注册 ---");
                return bean.error("该手机号已注册");
            }

            ///判断短信验证码是否正确
            Object code = JedisUtil.getObject(phone);
            if (!smsCode.equals(code)) {
                log.error("--- 手机验证码【" + smsCode + "】错误,正确验证码【" + code + "】 ---");
                return new ResponseBean(Constant.BUSI_ERROR_COD, "手机验证码错误", null);
            }

            merchant.setCreateTime(new Date());// 设置创建时间
            String salt = ObjectConvertUtils.randomGen(8);//创建salt盐值
            String merchantKey = MerchantUtil.generateMerchantKey(username); //创建商户key
            log.info("==== 生成随机字符串商户Key[" + merchantKey + "] ====");
            String passwordEncode = PasswordUtil.encrypt(username, password, salt);
            merchant.setMerchantKey(merchantKey);
            merchant.setSalt(salt);
            merchant.setLoginName(username);
            merchant.setRealName(username);
            merchant.setPassword(passwordEncode);
            merchant.setEmail(email);
            merchant.setPhone(phone);
            //正常：0、停用：1
            merchant.setStatus(0);
            merchant.setDelFlag(DictConstant.DEL_FLAG_0.toString());
            merchantService.addUser(merchant);//默认

            // ========================= 生成账户余额信息 ===============================
            //创建salt盐值
            String withdrawSalt = ObjectConvertUtils.randomGen(8);
            //提现密码初始值为6个0
            String withdrawPwdEncode = PasswordUtil.encrypt(username, "000000", withdrawSalt);
            BigDecimal initMoney = new BigDecimal(0);
            //获取商户ID
            int merchantId = merchantService.getUserByName(username).getMerchantId();
            log.info("==== 获取商户ID[" + merchantId + "] ====");
            //设置初始余额信息
            merchantWalletInfo.setMerchantId(merchantId);
            merchantWalletInfo.setFreezeMoney(initMoney);
            merchantWalletInfo.setMoney(initMoney);
            merchantWalletInfo.setWithdrawSalt(withdrawSalt);
            merchantWalletInfo.setWithdrawPassword(withdrawPwdEncode);
            merchantWalletInfo.setCreateTime(new Date());
            merchantWalletInfo.setCreateBy(username);
            merchantWalletService.addMerchantWalletInfo(merchantWalletInfo);

            bean.success("注册成功");
        } catch (Exception e) {
            e.printStackTrace();
            bean.error("注册失败");
        }

        return bean;
    }

    /**
     * 校验用户账号是否唯一<br>
     * 可以校验其他 需要检验什么就传什么。。。
     *
     * @param merchant
     * @return
     */
    @RequestMapping(value = "/checkOnlyUser", method = RequestMethod.GET)
    public ResponseBean checkOnlyUser(Merchant merchant) {
        ResponseBean bean = new ResponseBean();
        try {
            //通过传入信息查询新的用户信息
            Merchant user = merchantService.getOne(new QueryWrapper<Merchant>(merchant));
            if (user != null) {
                log.info("==== merchant register: [" + user.getLoginName() + "]账号存在 ====");
                return bean.error("用户账号已存在");
            }
        } catch (Exception e) {
            return bean.error(e.getMessage());
        }
        return bean.success("账号未被使用");
    }


    @AutoLog("忘记密码查询是否存在此用户")
    @PostMapping(value = "/queryUser")
    public ResponseBean queryUser(@RequestBody JSONObject jsonObject, Merchant merchant) {
        ResponseBean bean = new ResponseBean();

        String phone = jsonObject.getString("phone");
        String userName = jsonObject.getString("username");

        if (ObjectConvertUtils.isEmpty(phone) && ObjectConvertUtils.isEmpty(userName)) return bean.error("用户名或手机号不能为空");

        //手机号不为空
        if (ObjectConvertUtils.isNotEmpty(phone)) {
            if(phone.length() != 11) return bean.error("手机号格式不正确");
            merchant.setPhone(phone);
        }

        //用户名为空
        if (ObjectConvertUtils.isNotEmpty(userName)) {
            merchant.setLoginName(userName);
        }

        try {
            Merchant user = merchantService.getOne(new QueryWrapper<Merchant>(merchant));

            if (user != null) {
                Map<String, String> infoMap = new HashMap<String, String>();
                infoMap.put("userName", user.getLoginName());
                infoMap.put("phone", user.getPhone());
                return bean.success("操作成功", infoMap);
            }
        } catch (Exception e) {
            log.info(e.getMessage());
            return bean.error(e.getMessage());
        }

        return bean.error("该用户名或手机号未注册");
    }

}
